package com.msda.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageCompressor {

    private static final long MAX_SIZE_BYTES = 1024 * 1024; // 1MB

    public static byte[] compressToMaxSize(MultipartFile file) throws IOException {
        // 初始质量设置
        double quality = 0.9;
        byte[] compressedData;

        do {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            // 使用当前质量设置进行压缩
            Thumbnails.of(file.getInputStream())
                    .scale(1.0) // 保持原始尺寸
                    .outputQuality(quality)
                    .outputFormat("jpg") // 确保输出为JPEG格式
                    .toOutputStream(outputStream);

            compressedData = outputStream.toByteArray();

            // 如果仍然太大，降低质量继续尝试
            quality -= 0.1;

            // 防止质量降得过低（最低0.1）
            if (quality < 0.1) {
                break;
            }

        } while (compressedData.length > MAX_SIZE_BYTES);

        return compressedData;
    }
}
